/**
 * 入库管理模块
 * Created by zengtao on 2017/8/28.
 */
define(["jquery", "artTemplate","common","./search_rk_list","./search_rkth_list", "text!../../tpls/rukuguanli/rukuguanlimain.html",
        "text!../../tpls/rukuguanli/addruku.html","text!../../tpls/rukuguanli/addtuihuo.html",
        "text!../../tpls/rukuguanli/ruku_tuihuo.html","print"], function ($, art,common,search_rk_list,search_rkth_list, rukuguanlimain,addruku,addtuihuo,ruku_tuihuo) {
	var url = common.kcUrl(); 
	return function () {
		$("#mainpage").empty().append(rukuguanlimain);
		init_datetimepicker_ymd();
		search_rk_list(common.monthnow());
		
		//1.0	时间发生改变时请求入库列表数据
		$("#search_ruku_lists").on("change",".form_datetime",function(){
			var startDate = $("#ruku_begin_date_ipt").val();
			var endDate = $("#ruku_end_date_ipt").val();
			var keyWord = $("#ruku_keyword_ipt").val() || "";
			search_rk_list(startDate,endDate,keyWord);
		});
		
		//1.1	输入关键字回车后请求入库列表数据
		 $('#ruku_keyword_ipt').off("keypress").on("keypress",function(event){  
            if(event.keyCode == "13"){ 
            	var startDate = $("#ruku_begin_date_ipt").val();
    			var endDate = $("#ruku_end_date_ipt").val();
    			var keyWord = $("#ruku_keyword_ipt").val() || "";
    			search_rk_list(startDate,endDate,keyWord);  
            }  
        });
		
		
		// 新建入库操作页面
		$("#rkglAddRkBtn").on("click",function(){
			var navMenu = '<li >首页</li>'+
			'<li onclick=toRukuPage()>入库管理</li>'+
	        '<li class="active">入库</li>';
			$("#nav-top").empty().append(navMenu);
			$("#mainpage").empty();
			$("#mainpage").append(addruku);
			$("#rkgl_rklb_ul_svb").empty();
			$("#rkgl_rklb_ul_svb").append($($("#tpl_add_ruku_row").html()));
			init_datetimepicker_ymd();
			$("#sk_in_date").val(setdate_now());
			common.cloneOp("#sk_operator_id");//添加操作人选项
			/*var change_base_date = false;
			$("input.form_datetime2").off("change").on("change",function(){
				change_base_date = true;
			})*/
			
			// 用来显示提示物品内容的ul
			var searchTplHtml = '<ul id="searchresult" style="position:absolute;top:34px;z-index:998;width:212px;border:1px solid #ccc;border-top:none;max-height:240px;overflow-y:auto;overflow-x:hidden;text-align:left;"></ul>';
			var $searchTplHtml = $(searchTplHtml);
			
			var searchTplHtml2 = '<ul id="searchresult2" style="position:absolute;top:34px;z-index:998;width:212px;border:1px solid #ccc;border-top:none;max-height:240px;overflow-y:auto;overflow-x:hidden;text-align:left;"></ul>';
			var $searchTplHtml2 = $(searchTplHtml2);
			
			// 新增入库 - 
			// 物品类型输入框获取焦点时显示所有物品类型信息
			$("#rkgl_rklb_ul_svb").off("focus").on("focus",".searchByType",function(){
				$_that = $(this);
				var $_that_search_by_name = $_that.parent().siblings(".rkgl_rk_ggmc");
				$("#searchresult2").remove();
				var index = layer.load(2, {time: 5*1000});
				$.get(url + "inventory/inventorytypeList.shtml",function(res){
					//console.log(res);
					layer.close(index);
					if(res.status == 1){
						layer.msg("网络忙,请稍后重试");
						return
					}
				    var result = eval('(' + res.result + ')');
				    var wplxListHtml = art.render($("#tpl_add_search_type_row").html(), {
				        result: result   
				    });
				   
				    var $wplxListHtml = $(wplxListHtml);
				    $_that.parent().append($searchTplHtml);//添加提示类型的容器
				    $("#searchresult").empty().append($wplxListHtml);//添加提示的物品类型内容
				    
				    $("#searchresult li").on("click.copytext",function(){
				    	$(this).parent().parent().children("input").val($(this).data("sk_type_name"));
				    	var sk_type_id = $(this).data("sk_type_id");
				    	var $_that = $(this);
				    	$(this).parent().parent().siblings().children("input").val("");
				    	var index = layer.load(2, {time: 5*1000});
				    	// 请求物品类型下的物品信息
						$.get(url + "inventory/inventoryList.shtml?type="+sk_type_id,function(res){
							//console.log(res);
							layer.close(index);
							if(res.status == 1){
								layer.msg("网络忙,请稍后重试");
								return
							}
						    var result = eval('(' + res.result + ')');
						    var wplxListHtml = art.render($("#tpl_search_type_info").html(), {
						        result: result   
						    });
						   
						    var $wplxListHtml = $(wplxListHtml);
						    $_that_search_by_name.append($searchTplHtml2);//添加物品名称提示的容器
						    $("#searchresult2").empty().append($wplxListHtml);
						    // 物品名称的每行
						    $("#searchresult2 li").on("click.copytext2",function(){
						    	$(this).parent().parent().children("input").val($(this).data("sk_type_name"));//物品类型名称
						    	$(this).parent().parent().children("input").data("sk_inventory_id",$(this).data("sk_inventory_id"));//保存规格名称ID
						    	$(this).parent().parent().siblings(".rkgl_rk_sccj").children("input").val($(this).data("sk_facturers_name"));
						    	$(this).parent().parent().siblings(".rkgl_rk_gys").children("input").val($(this).data("sk_dealer_name"));
						    	$(this).parent().parent().siblings(".rkgl_rk_wpdj").children("input").val($(this).data("sk_inventory_price_in"));//入库价格
						    	$(this).parent().parent().siblings(".rkgl_rk_ph").children("input").focus();
						    	$("#searchresult2").remove();
						    });
						});
				    	
				    });
				    
				})
			});
			
			// 物品类型输入框失去焦点时移除提示框
			$("#rkgl_rklb_ul_svb").on("blur",".searchByType",function(){
		    	setTimeout(function() {
		    		$("#searchresult").remove();  
		        }, 200);
		    	
		    });
			
			//规格名称获取焦点时提示所有物品名称内容
			$("#rkgl_rklb_ul_svb").off("focus").on("focus",".searchByName",function(){
				$_that = $(this);
				var index = layer.load(2, {time: 5*1000});
				$.post(url + "inventory/autoinventoryList.shtml",{name:""},function(res){
					layer.close(index);
					if(res.status == 1){
						layer.msg("网络忙,请稍后重试");
						return
					}
					var result = eval('(' + res.result + ')');
					//console.log(result)
					if(result.length == 0){
						$("#searchresult2").remove();
						return
					}
				    var wplxListHtml = art.render($("#tpl_search_type_info").html(), {
				        result: result   
				    });				   
				    var $wplxListHtml = $(wplxListHtml);
				    $_that.parent().append($searchTplHtml2);
				    $("#searchresult2").empty().append($wplxListHtml);
				    $("#searchresult2 li").on("click",function(){
				    	$(this).parent().parent().siblings(".rkgl_rk_wpbm").children("input").val($(this).data("sk_inventory_type_name"));//物品类型
				    	$(this).parent().parent().children("input").data("sk_inventory_id",$(this).data("sk_inventory_id"));//物品ID
				    	$(this).parent().parent().children("input").val($(this).data("sk_type_name"));//物品名称
				    	$(this).parent().parent().siblings(".rkgl_rk_sccj").children("input").val($(this).data("sk_facturers_name"));//生产厂家
				    	$(this).parent().parent().siblings(".rkgl_rk_gys").children("input").val($(this).data("sk_dealer_name"));//供应商
				    	$(this).parent().parent().siblings(".rkgl_rk_wpdj").children("input").val($(this).data("sk_inventory_price_in"));//入库价格
				    	$(this).parent().parent().siblings(".rkgl_rk_ph").children("input").focus();
				    	$(this).parent("#searchresult2").remove();
				    });
				});
			})
			
			//新增入库 - 输入规格名称查询提示信息
			$("#rkgl_rklb_ul_svb").off("keyup.byname").on("keyup.byname",".searchByName",function(){
				var keyword = $(this).val() || "";
				$(this).parent().siblings().children("input").val("");
				$_that = $(this);
				var index = layer.load(2, {time: 5*1000});
				$.post(url + "inventory/autoinventoryList.shtml",{name:keyword},function(res){
					layer.close(index);
					var result = eval('(' + res.result + ')');
					//console.log(result)
					if(result.length == 0){
						$("#searchresult2").empty().append("<li>暂无数据</li>");
						return
					}
				    var wplxListHtml = art.render($("#tpl_search_type_info").html(), {
				        result: result   
				    });				   
				    var $wplxListHtml = $(wplxListHtml);
				    $_that.parent().append($searchTplHtml2);
				    $("#searchresult2").empty().append($wplxListHtml);
				    
				    $("#searchresult2 li").on("click",function(){
				    	$(this).parent().parent().siblings(".rkgl_rk_wpbm").children("input").val($(this).data("sk_inventory_type_name"));//物品类型
				    	$(this).parent().parent().children("input").data("sk_inventory_id",$(this).data("sk_inventory_id"));//物品ID
				    	$(this).parent().parent().children("input").val($(this).data("sk_type_name"));//物品名称
				    	$(this).parent().parent().siblings(".rkgl_rk_sccj").children("input").val($(this).data("sk_facturers_name"));//生产厂家
				    	$(this).parent().parent().siblings(".rkgl_rk_gys").children("input").val($(this).data("sk_dealer_name"));//供应商
				    	$(this).parent().parent().siblings(".rkgl_rk_wpdj").children("input").val($(this).data("sk_inventory_price_in"));//入库价格
				    	$(this).parent().parent().siblings(".rkgl_rk_ph").children("input").focus();
				    	$(this).parent("#searchresult2").remove();
				    });
				});
				
			});
			
			// 输入物品input-失去焦点时移除规格名称的提示框
			$("#rkgl_rklb_ul_svb").on("blur",".searchByName",function(){
		    	setTimeout(function() {
		    		$("#searchresult2").remove();  
		        }, 200);
		    	
		    });
			
			// 输入数量后回车键增加一行
			$("#rkgl_rklb_ul_svb").off("keypress").on("keypress","input.sk_in_operation_num,input.sk_in_price",function(event){
				if(event.keyCode == "13"){ 
					$(this).parent().siblings("span.rkgl_rk_cz").find("img.add_row_ctrl").trigger("click.addrow");
					//console.log($(this))
	            }  
		    });
			
			//计算入库每行的总金额
			$("#rkgl_rklb_ul_svb").off("keyup.count").on("keyup.count",".sk_in_operation_num",function(){
				var count = parseInt($(this).val());
				var price = parseFloat($(this).parent().siblings(".rkgl_rk_wpdj").children("input").val());
				if(isNaN(count) || isNaN(price)){
					return
				}
				$(this).parent().siblings(".rkgl_rk_wpzj").children("input").val(common.float_num2(count*price));
			});	
			$("#rkgl_rklb_ul_svb").off("keyup.price").on("keyup.price",".sk_in_price",function(){
				var count = parseInt($(this).parent().siblings(".rkgl_rk_rksl").children("input").val());
				var price = parseFloat($(this).val());
				if(isNaN(count) || isNaN(price)){
					return
				}
				$(this).parent().siblings(".rkgl_rk_wpzj").children("input").val(common.float_num2(count*price));
			});	
			//增加一行
			$("#mainpage").off("click.addrow").on("click.addrow",".add_row_ctrl",function(){
				var $addRow = $($("#tpl_add_ruku_row").html());
				var lastXh = $("#rkgl_rklb_ul_svb .list_jl_view_1503:last").children(".rkgl_rk_xh").text() || 0;
				//新增的序号递增1，加入到ul末尾
				$addRow.find(".rkgl_rk_xh").text(parseInt(lastXh) + 1);							
				$("#rkgl_rklb_ul_svb").append($addRow);
				init_datetimepicker_ymd();
				if($("#rkgl_rklb_ul_svb")[0].scrollHeight>$("#rkgl_rklb_ul_svb")[0].clientHeight||$("#rkgl_rklb_ul_svb")[0].offsetHeight>$("#rkgl_rklb_ul_svb")[0].clientHeight){ 
					$(".title-pr").css("padding-right","17px");
				} 
			});
			//删除一行
			$("#mainpage").off("click.delrow").on("click.delrow",".con_row_ctrl",function(){
				if($(this).parent().siblings(".rkgl_rk_xh").text() == 1){
					return
				}
				//改变删除行之后的每行序号
				$(this).parent().parent().nextAll().find(".rkgl_rk_xh").each(function(){
					var count = parseInt($(this).text());
					$(this).text(count - 1);
				});
				$(this).parent().parent().remove();//删除自己所在的行
			});
			
			//入库管理 - 新增入库 - 提交
			$("#saveAddBtn").on("click",function(){
				var sendData = [];
				var printData = [];
				var flag = true;
				var sk_in_date = $("#sk_in_date").val();
				var sk_in_operation_time = common.getNowFormatDate();
				$("#rkgl_rklb_ul_svb > li").each(function(v,i){
					var sk_inType = $(this).find("input.searchByType").val();//物品类型
					var sk_in_inventory_id = $(this).find(".searchByName").data("sk_inventory_id");
					var sk_in_inventory_name = $(this).find(".searchByName").val(); //'物品名称'
					var sk_in_batch = $(this).find(".sk_in_batch").val();
					var sk_in_price = common.float_num2(($(this).find(".sk_in_price").val()));
					var sk_in_operation_type = 0;
					var sk_in_operation_num = $(this).find(".sk_in_operation_num").val();
					var sk_in_operator = $("#sk_operator_id").val();
					
					var sk_product_date = $(this).find(".sk_product_date").val() || "";
					var sk_valid_date = $(this).find(".sk_valid_date").val();
					var sk_notes = $("#sk_notes").val();
					var $_this = $(this);
					function check_ipt(inputclass){
						warnMsg3($_this,inputclass,"带 * 项为必填项");		            	
		            	flag = false;
		            	return false;
					}
					if(!sk_inType){
						check_ipt(".searchByType");
						return false;
					}
					
					if(!sk_in_inventory_name || !sk_in_inventory_id){
		            	check_ipt(".searchByName");
		            	return false;
					}
					if(!sk_in_batch){
						check_ipt(".sk_in_batch");
						return false;
					}
					if(!sk_in_operation_num){
						check_ipt(".sk_in_operation_num");
						return false;
					}
					if(!sk_in_batch){
						check_ipt(".sk_in_batch");
						return false;
					}
					if(!sk_in_price){
						check_ipt(".sk_in_price");
						return false;
					}
					if(!sk_valid_date){
						check_ipt(".sk_valid_date");
						return false;
					}
					var list_obj = {
						  sk_in_inventory_id:sk_in_inventory_id,
				          sk_in_batch:sk_in_batch,
				          sk_in_price:sk_in_price,
				          sk_in_operation_type:sk_in_operation_type,
				          sk_in_operation_num:sk_in_operation_num,
				          sk_in_operator:sk_in_operator,
				          sk_in_date:sk_in_date,
				          sk_product_date:sk_product_date,
				          sk_valid_date:sk_valid_date,
				          sk_notes:sk_notes	
					};
					sendData.push(list_obj);
					var print_obj = {
							sk_in_inventory_id:sk_in_inventory_id,
							sk_inventory_name:sk_in_inventory_name,
							sk_in_price:sk_in_price,
							sk_in_operation_num:sk_in_operation_num,
							sk_in_batch:sk_in_batch,
							sk_product_date:sk_product_date,
					        sk_valid_date:sk_valid_date,
					        sk_in_operation_time:sk_in_operation_time
						};
					printData.push(print_obj);
				});
				if(!flag){
					return
				}
				//console.log(sendData);
				if (window.localStorage) {
				    localStorage.setItem("sk_in_data", JSON.stringify(printData));	//保存当前录入信息到本地存储
				} 
				var index = layer.load(2, {time: 5*1000});
				$(this).prop('disabled', true).addClass("waiting");
				var $_that = $(this);
				$.ajax({
					url: url + "stock/insertInstock.shtml" ,
					type: "POST",
					async:false,
					data:{inarray:JSON.stringify(sendData)},
					success: function(res){
						layer.close(index);
						//console.log(res);
						$_that.prop('disabled', false).removeClass("waiting");
						if(res.status == 1){
		            		layer.msg("网络忙,请稍后重试");
		            		return
		            	}
		        		layer.confirm('入库成功，是否打印入库单', {
						      icon: 3,
						      title: '提示'
						    }, function (index) {
						    	var sk_in_bill = res.result;
						    	var getDataBegin = layer.load(4, {time: 6*1000});
								$.ajax({
									type: "GET",
									url: url + "stock/instockList.shtml?type=0&bill="+sk_in_bill,
									success: function(res){
										layer.close(getDataBegin);
										var result = eval('(' + res.result + ')');
										//console.log(result);
										var rkList = art.render($("#tpl_print_sk_in_bill").html(), {
											result: result   
										});
										/*var winname = window.open('', "_blank",'');
									    winname.document.body.innerHTML = rkList;
									    winname.print();*/
									    $("#myPrintId").empty().append($(rkList)).print({
										    globalStyles:true,//是否包含父文档的样式，默认为true
										    mediaPrint:false,//是否包含media='print'的链接标签。会被globalStyles选项覆盖，默认为false
										    stylesheet:null,//外部样式表的URL地址，默认为null
										    noPrintSelector:".no-print",//不想打印的元素的jQuery选择器，默认为".no-print"
										    iframe:true,//是否使用一个iframe来替代打印表单的弹出窗口，true为在本页面进行打印，false就是说新开一个页面打印，默认为true
										    append:null,//将内容添加到打印内容的后面
										    prepend:null,//将内容添加到打印内容的前面，可以用来作为要打印内容
										    deferred:$.Deferred().done(function(){
										    	$("#rkgl_rklb_ul_svb > li:not(:first)").remove();
										    	$("#rkgl_rklb_ul_svb > li").find("input").val('');
								        		$("#sk_notes").val("");
										    	$("#myPrintId").empty();
										    	//$("#kc_rukugl_a").trigger("click");
											 })//回调函数
										});    
									}
								});
						        layer.close(index);
						    },function(index){
						    	$("#rkgl_rklb_ul_svb > li:not(:first)").remove();
						    	$("#rkgl_rklb_ul_svb > li").find("input").val('');
				        		$("#sk_notes").val("");
						    });
					}
				});
				//$("#kc_rukugl_a").trigger("click");
			});
			
			//入库管理 - 新增入库 - 取消
			$("#cancelAddBtn").on("click",function(){
				var flag = true;
				$("#rkgl_rklb_ul_svb input").each(function(){
					if($(this).val()){
						flag = false;
						return false;
					}
				});
				if(!flag){
	            	var $_that = $(this);
				    layer.confirm('确认取消？', {
				      icon: 3,
				      title: '提示'
				    }, function (index) {
				      $("#rkgl_rklb_ul_svb").find("input").val("");	
				      layer.close(index);
				    });
	        	}else{
	        		$("#kc_rukugl_a").trigger("click");//返回入库管理页面
	        	}
				
			});
			
		});

		//2.1	入库退货按钮跳转退货操作页面
		$("#rkglAddThBtn").on("click",function(){
			var sk_in_id_array = [];
			$("#rkgl_wpxxlist_ul_svb > li").find("input[name='out_checkbox']").each(function(i,v){
				if($(this).is(':checked')){
					sk_in_id_array.push($(this).siblings(".sk_in_inventory_id").data("inid").toString());
				}
				
			});
			if(sk_in_id_array.length == 0){
				layer.msg("请选择需要退货的物品");
				return
			}
			var navMenu = '<li style="padding:0 6px;">首页</li>'+
			'<li style="padding:0 6px;" onclick=toRukuPage()>入库管理</li>'+
			'<li style="padding:0 6px;" class="active">退货</li>';
			$("#nav-top").empty().append(navMenu);
			$("#mainpage").empty().append(addtuihuo);
			init_datetimepicker_ymd();
			//console.log(sk_in_id_array);
			$("input.form_datetime2").val(setdate_now())
			common.cloneOp("#sk_operator_id2");//添加操作人选项
			/*var change_base_date = false;
			$("input.form_datetime2").off("change").on("change",function(){
				change_base_date = true;
			})*/
			$.ajax({
				url: url + "stock/instockListByarray.shtml",
				type: "POST",
				data:{
					array:sk_in_id_array,
				},
				traditional :true,
				success: function(res){
					var result = eval('(' + res.result + ')');
					var rkList = art.render($("#tpl_add_tuihuolist").html(), {
						result: result   
					});					
					var $rkList = $(rkList);
					$("#rkgl_addrkth_ul_svb").append($rkList);
					setPaddingR("#rkgl_addrkth_ul_svb",".title-pr",410);
					
					try{
						$("#rkgl_addrkth_ul_svb input.out_count").eq(0).focus();
					} catch(e){};
					
					// 显示和隐藏操作按钮
				    $("#rkgl_addrkth_ul_svb > li").hover(function(){
				    	$(this).children(".jbxx_wplx_cz").addClass("opacity_ctrl");
				    	$(this).children(".jbxx_wplx_cz").removeClass("opacity_noctrl");
				    },function(){
				    	$(this).children(".jbxx_wplx_cz").addClass("opacity_noctrl");
						$(this).children(".jbxx_wplx_cz").removeClass("opacity_ctrl");
				    });
				    
				    // 入库退货列表 - 删除不需要退货的行
					$(".delete_img").on("click",function(){
						var $_that = $(this);
					    layer.confirm('确认删除？', {
					      icon: 3,
					      title: '提示'
					    }, function (index) {
					  	//改变删除行之后的每行序号
					      $_that.parent().parent().nextAll().find(".rkgl_addrkth_xh").each(function(){
								var count = parseInt($(this).text());
								$(this).text(count - 1);
							});
					      $_that.parent().parent().remove();//删除自己所在的行
					      layer.close(index);
					    });
					});
					
					// 输入数量后回车键切换光标至下一个输入框
					$("#mainpage").off("keypress").on("keypress","input.out_count",function(event){
						if(event.keyCode == "13"){ 
							try{
								$(this).parent().parent("li").next().find("input.out_count").focus();
							} catch(e){}
			            }  
				    });
					
					//计算入库退货每行的总金额
					$("#rkgl_addrkth_ul_svb").off("keyup.count").on("keyup.count",".out_count",function(){
						var count = parseInt($(this).val());
						var price = parseFloat($(this).parent().siblings(".rkgl_addrkth_rkdj").text());
						if(isNaN(count) || isNaN(price)){
							$(this).parent().siblings(".rkgl_addrkth_thjg").text("");
							return
						}
						$(this).parent().siblings(".rkgl_addrkth_thjg").text(common.float_num2(count*price));
					});	
					
					//入库管理 - 新增入库退货 - 提交
					$("#saveAddBtn").on("click",function(){
						var sendData = [];
						var printData = [];
						var flag = true;
						var sk_in_date = $("#sk_in_date").val();
						var sk_in_operation_time = common.getNowFormatDate();
						$("#rkgl_addrkth_ul_svb > li").each(function(v,i){
							var sk_in_id = $(this).data("skinid"); //'ID'
							var sk_in_inventory_id = $(this).find(".rkgl_addrkth_wpbm").text();
							var sk_in_num = parseInt($(this).find(".rkgl_addrkth_kcsl").text());
							var sk_in_operation_num = parseInt($(this).find(".rkgl_addrkth_thsl").children("input").val());
							var sk_in_operator = $("#sk_operator_id2").val();
							var sk_notes = $("#sk_notes").val();
							var $_this = $(this);
							
							var sk_in_bill = $(this).find(".rkgl_addrkth_rkdh").text();
							var sk_inventory_name = $(this).find(".rkgl_addrkth_ggmc").text();
							var sk_in_price = $(this).find(".rkgl_addrkth_rkdj").text();
							
							if(!sk_in_operation_num){
				            	var $_this = $(this);
				            	warnMsg3($_this,".out_count","请填写退货数量");
				            	flag = false;
				            	return false;
				            }
							/*if(sk_in_operation_num > sk_in_num){
				            	var $_this = $(this);
				            	warnMsg3($_this,".out_count","退货数量大于入库数量");
				            	flag = false;
				            	return false;
				            }*/
							var list_obj = {
								  sk_in_id:sk_in_id,
								  sk_in_inventory_id:sk_in_inventory_id,
						          sk_in_operation_num:sk_in_operation_num,
						          sk_in_operator:sk_in_operator,
						          sk_in_date:sk_in_date,
						          sk_notes:sk_notes	
							};
							
							
							var print_obj = {
									sk_in_inventory_id:sk_in_inventory_id,
									sk_inventory_name:sk_inventory_name,
									sk_in_price:sk_in_price,
									sk_in_operation_num:sk_in_operation_num,
									sk_in_operation_time:sk_in_operation_time,
									sk_in_bill:sk_in_bill	
								};
							
							sendData.push(list_obj);
							printData.push(print_obj);
						});
						if(!flag){
							return
						}
						//console.log(sendData);
						if (window.localStorage) {
						    localStorage.setItem("sk_in_back_data", JSON.stringify(printData));	//保存当前录入信息到本地存储
						} 
						var index = layer.load(2, {time: 5*1000});
						$(this).prop('disabled', true).addClass("waiting");
						var $_that = $(this);
						$.ajax({
							url: url + "stock/insertInstockback.shtml" ,
							type: "POST",
							async:false,
							data:{inarray:JSON.stringify(sendData)},
							success: function(res){
								layer.close(index);
								$_that.prop('disabled', false).removeClass("waiting");
								if(res.status == 1){
				            		layer.msg("网络忙,请稍后重试");
				            		return
				            	}
				        		//console.log(JSON.parse(localStorage.getItem("sk_in_back_data")));
			        		  layer.confirm('退货成功，是否打印退货单', {
							      icon: 3,
							      title: '提示'
							    }, function (index) {
							    	var sk_bill = $("#rkgl_addrkth_ul_svb > li").eq(0).find("span.rkgl_addrkth_rkdh").text();
							    	var getDataBegin = layer.load(4, {time: 6*1000});
							    	$.ajax({
										type: "GET",
										url: url + "stock/instockList.shtml?type=1&bill="+sk_bill,
										success: function(res){
											layer.close(getDataBegin);
											//var result2 = eval('(' + res.result + ')');
											//console.log(result2);
											var result = JSON.parse(localStorage.getItem("sk_in_back_data"));
											result[0].sk_in_operation_time = eval('(' + res.result + ')')[0].sk_in_operation_time;
											var rkList = art.render($("#tpl_print_sk_in_back_bill2").html(), {
												result: result   
											});
											/*var winname = window.open('', "_blank",'');
										    winname.document.body.innerHTML = rkList;
										    winname.print();*/
										    $("#myPrintId").empty().append($(rkList)).print({
											    globalStyles:true,//是否包含父文档的样式，默认为true
											    mediaPrint:false,//是否包含media='print'的链接标签。会被globalStyles选项覆盖，默认为false
											    stylesheet:null,//外部样式表的URL地址，默认为null
											    noPrintSelector:".no-print",//不想打印的元素的jQuery选择器，默认为".no-print"
											    iframe:true,//是否使用一个iframe来替代打印表单的弹出窗口，true为在本页面进行打印，false就是说新开一个页面打印，默认为true
											    append:null,//将内容添加到打印内容的后面
											    prepend:null,//将内容添加到打印内容的前面，可以用来作为要打印内容
											    deferred:$.Deferred().done(function(){
											    	$("#myPrintId").empty();
											    	$("#kc_rukugl_a").trigger("click");
												 })//回调函数
											});    
										}
									});
							        layer.close(index);
							    },function(index){
							    	$("#kc_rukugl_a").trigger("click");
							    });
							}
						});
						
					});
					
					//入库管理 - 新增入库退货 - 取消
					$("#cancelAddBtn").on("click",function(){
						var $_that = $(this);
					    layer.confirm('确认取消？', {
					      icon: 3,
					      title: '提示'
					    }, function (index) {
					      $("#kc_rukugl_a").trigger("click");
					      layer.close(index);
					    });
					});
				}
			});
		});

		//3.1  退货记录按钮导入退库记录列表页面
		$("#rkglThjlBtn").on("click",function(){
			var navMenu = '<li style="padding:0 6px;">首页</li>'+
			'<li style="padding:0 6px;" onclick=toRukuPage()>入库管理</li>'+
			'<li style="padding:0 6px;" class="active">入库退货记录</li>';
			$("#nav-top").empty().append(navMenu);
			$("#mainpage").empty().append(ruku_tuihuo);
			init_datetimepicker_ymd();
			search_rkth_list(common.monthnow());//默认请求最近一个月的数据
			
			//3.11	时间发生改变时请求数据
			$("#search_ruku_lists").on("change",".form_datetime",function(){
				var startDate = $("#ruku_begin_date_ipt").val();
				var endDate = $("#ruku_end_date_ipt").val();
				var keyWord = $("#ruku_keyword_ipt").val() || "";
				search_rkth_list(startDate,endDate,keyWord);//查询数据并显示 
			});
			
			//3.12	输入关键字回车后请求数据
			 $('#search_ruku_lists').on("keypress","#ruku_keyword_ipt",function(event){  
	            if(event.keyCode == "13"){ 
	            	var startDate = $("#ruku_begin_date_ipt").val();
	    			var endDate = $("#ruku_end_date_ipt").val();
	    			var keyWord = $("#ruku_keyword_ipt").val() || "";
	    			search_rkth_list(startDate,endDate,keyWord); //查询数据并显示 
	            }  
	        });
			 
			// 打印退货记录
			$("#print_sk_in_backlist").on("click.print_in_back",function(){
				var sk_bill,sk_time;
				var sel_sk_in_back_bill = $('#rk_tuihuo_list .list_jl_view_1503').each(function(v,i){
					if($(this).hasClass("list_active")){
						sk_bill = $(this).find(".sk_in_bill_ipt").val();
						sk_time = $(this).find(".rkgl_rkthjl_thsj").val();
						return sk_bill,sk_time;
					}
				});
				//console.log(sk_bill,sel_sk_in_back_bill)
				var getDataBegin = layer.load(4, {time: 6*1000});
				$.ajax({
					type: "GET",
					url: url + "stock/instockList.shtml?type=1&bill="+sk_bill,
					success: function(res){
						layer.close(getDataBegin);
						var result = eval('(' + res.result + ')');
						//console.log(result);
						var rkList = art.render($("#tpl_print_sk_in_back_bill").html(), {
							result: result   
						});
						/*var winname = window.open('', "_blank",'');
					    winname.document.body.innerHTML = rkList;
					    winname.print();*/
					    $("#myPrintId").empty().append($(rkList)).print({
						    globalStyles:true,//是否包含父文档的样式，默认为true
						    mediaPrint:false,//是否包含media='print'的链接标签。会被globalStyles选项覆盖，默认为false
						    stylesheet:null,//外部样式表的URL地址，默认为null
						    noPrintSelector:".no-print",//不想打印的元素的jQuery选择器，默认为".no-print"
						    iframe:true,//是否使用一个iframe来替代打印表单的弹出窗口，true为在本页面进行打印，false就是说新开一个页面打印，默认为true
						    append:null,//将内容添加到打印内容的后面
						    prepend:null,//将内容添加到打印内容的前面，可以用来作为要打印内容
						    deferred:$.Deferred().done(function(){
						    	$("#myPrintId").empty();
							 })//回调函数
						});    
					}
				});
			});
		});
		
		//4.1 打印入库记录功能   
		$("#dyrkdBtn").on("click",function(){
			var sk_in_bill,sk_time;
			var sel_sk_in_bill = $('#rkgl_rklist_ul_svb .list_jl_view_1503').each(function(v,i){
				if($(this).hasClass("list_active")){
					sk_in_bill = $(this).find(".sk_in_bill_ipt").val();
					sk_time = $(this).find(".rkgl_rkjl_rksj input").val();
					return sk_in_bill,sk_time;
				}
			});
			var getDataBegin = layer.load(4, {time: 6*1000});
			$.ajax({
				type: "GET",
				url: url + "stock/instockList.shtml?type=0&bill="+sk_in_bill,
				success: function(res){
					layer.close(getDataBegin);
					var result = eval('(' + res.result + ')');
					//console.log(result);
					var rkList = art.render($("#tpl_print_sk_in_bill").html(), {
						result: result   
					});
					/*var winname = window.open('', "_blank",'');
				    winname.document.body.innerHTML = rkList;
				    winname.print();*/
				    $("#myPrintId").empty().append($(rkList)).print({
					    globalStyles:true,//是否包含父文档的样式，默认为true
					    mediaPrint:false,//是否包含media='print'的链接标签。会被globalStyles选项覆盖，默认为false
					    stylesheet:null,//外部样式表的URL地址，默认为null
					    noPrintSelector:".no-print",//不想打印的元素的jQuery选择器，默认为".no-print"
					    iframe:true,//是否使用一个iframe来替代打印表单的弹出窗口，true为在本页面进行打印，false就是说新开一个页面打印，默认为true
					    append:null,//将内容添加到打印内容的后面
					    prepend:null,//将内容添加到打印内容的前面，可以用来作为要打印内容
					    deferred:$.Deferred().done(function(){
					    	$("#myPrintId").empty();
						 })//回调函数
					});    
				}
			});
		});
	};
});